package com.zhika.zishi.fragments;

import android.app.Fragment;
import android.os.Bundle;

import com.zhika.zishi.interfaces.BackPressedInterface;

/**
 * Created by shi-02 on 2015/5/6.
 * 处理物理back键的事件的fragment继承此fragment,能有效的解决
 */
public abstract class BackHandlerFragment extends Fragment {

    private BackPressedInterface backPressedInterface;

    /**
     * 所有继承BackHandledFragment的子类都将在这个方法中实现物理Back键按下后的逻辑
     * FragmentActivity捕捉到物理返回键点击事件后会首先询问Fragment是否消费该事件
     * 如果没有Fragment消息时FragmentActivity自己才会消费该事件
     */
    public abstract boolean onBackPressed();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(!(getActivity() instanceof BackPressedInterface)){
            throw new ClassCastException("Hosting Activity must implement BackPressedInterface");
        }else{
            this.backPressedInterface = (BackPressedInterface)getActivity();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //告诉Activity，当前Fragment在栈顶
        backPressedInterface.setSelectedFragment(this);
    }
}
